import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import '../style/tokens/spacing.dart';
import '../style/tokens/typography.dart';
import '../style/tokens/borders.dart';

/// 全局Loading工具类
/// 基于flutter_smart_dialog实现的全局加载状态管理
/// 遵循局部化反馈设计准则，支持全局和局部loading状态管理
class UILoadingUtil {
  /// 显示全局loading
  /// [message] 加载提示信息
  /// [barrierDismissible] 是否允许点击遮罩关闭
  /// [maskColor] 遮罩颜色
  static Future<void> showGlobal({
    String? message,
    bool barrierDismissible = false,
    Color? maskColor,
  }) async {
    await SmartDialog.showLoading(
      maskColor: maskColor ?? Colors.black.withOpacity(0.3),
      clickMaskDismiss: barrierDismissible,
      usePenetrate: false,
      builder: (context) => UIGlobalLoadingWidget(message: message),
    );
  }

  /// 隐藏全局loading
  static Future<void> hideGlobal() async {
    await SmartDialog.dismiss(status: SmartStatus.loading);
  }
  /// 显示确认对话框
  /// [title] 标题
  /// [content] 内容
  /// [confirmText] 确认按钮文本
  /// [cancelText] 取消按钮文本
  /// [barrierDismissible] 是否允许点击遮罩关闭
  static Future<bool?> showConfirm({
    required String title,
    required String content,
    String confirmText = '确定',
    String cancelText = '取消',
    bool barrierDismissible = true,
  }) {
    return SmartDialog.show(
      clickMaskDismiss: barrierDismissible,
      builder: (context) => UIConfirmDialog(
        title: title,
        content: content,
        confirmText: confirmText,
        cancelText: cancelText,
      ),
    ).then((result) => result as bool?);
  }

  /// 显示自定义对话框
  /// [builder] 对话框构建器
  /// [barrierDismissible] 是否允许点击遮罩关闭
  static Future<T?> showCustomDialog<T>({
    required Widget Function(BuildContext context) builder,
    bool barrierDismissible = true,
  }) {
    return SmartDialog.show<T>(
      clickMaskDismiss: barrierDismissible,
      builder: builder,
    );
  }

  /// 关闭所有弹窗
  static Future<void> dismissAll() async {
    await SmartDialog.dismiss(status: SmartStatus.allDialog);
  }
}


/// 全局Loading组件
class UIGlobalLoadingWidget extends StatelessWidget {
  const UIGlobalLoadingWidget({
    super.key,
    this.message,
  });

  final String? message;

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    return Center(
      child: Container(
        constraints: BoxConstraints(
          maxWidth: MediaQuery.of(context).size.width * 0.8,
          minWidth: 120,
        ),
        decoration: BoxDecoration(
          color: colorScheme.surface,
          borderRadius: BorderRadius.circular(UIBorders.radiusXL),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 8,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        padding: const EdgeInsets.all(UISpacing.xl),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            UIGradientProgressIndicator(
              size: 36,
              strokeWidth: 3,
              color: colorScheme.primary,
            ),
            if (message != null) ...[
              const SizedBox(height: UISpacing.md),
              Text(
                message!,
                textAlign: TextAlign.center,
                style: UITextStyles.bodyMedium.copyWith(
                  color: colorScheme.onSurface,
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }
}

/// 渐变进度指示器
class UIGradientProgressIndicator extends StatefulWidget {
  const UIGradientProgressIndicator({
    super.key,
    this.size = 24,
    this.strokeWidth = 2,
    this.color,
    this.duration = const Duration(milliseconds: 1200),
  });

  final double size;
  final double strokeWidth;
  final Color? color;
  final Duration duration;

  @override
  State<UIGradientProgressIndicator> createState() => _UIGradientProgressIndicatorState();
}

class _UIGradientProgressIndicatorState extends State<UIGradientProgressIndicator>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: widget.duration,
      vsync: this,
    )..repeat();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final color = widget.color ?? Theme.of(context).colorScheme.primary;

    return SizedBox(
      width: widget.size,
      height: widget.size,
      child: AnimatedBuilder(
        animation: _controller,
        builder: (context, child) {
          return Transform.rotate(
            angle: _controller.value * 2.0 * 3.14159,
            child: CustomPaint(
              size: Size(widget.size, widget.size),
              painter: _GradientCircularProgressPainter(
                color: color,
                strokeWidth: widget.strokeWidth,
                progress: 0.75,
              ),
            ),
          );
        },
      ),
    );
  }
}

/// 渐变圆形进度绘制器
class _GradientCircularProgressPainter extends CustomPainter {
  _GradientCircularProgressPainter({
    required this.color,
    required this.strokeWidth,
    required this.progress,
  });

  final Color color;
  final double strokeWidth;
  final double progress;

  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final radius = (size.width - strokeWidth) / 2;

    // 绘制背景圆环
    final bgPaint = Paint()
      ..color = color.withOpacity(0.1)
      ..strokeWidth = strokeWidth
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round;

    canvas.drawCircle(center, radius, bgPaint);

    // 绘制进度圆环
    final progressPaint = Paint()
      ..strokeWidth = strokeWidth
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round;

    // 创建渐变
    progressPaint.shader = SweepGradient(
      colors: [
        color.withOpacity(0.1),
        color,
        color.withOpacity(0.1),
      ],
      stops: const [0.0, 0.5, 1.0],
    ).createShader(Rect.fromCircle(center: center, radius: radius));

    canvas.drawArc(
      Rect.fromCircle(center: center, radius: radius),
      -3.14159 / 2, // 从顶部开始
      2 * 3.14159 * progress,
      false,
      progressPaint,
    );
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

/// 确认对话框组件
class UIConfirmDialog extends StatelessWidget {
  const UIConfirmDialog({
    super.key,
    required this.title,
    required this.content,
    this.confirmText = '确定',
    this.cancelText = '取消',
  });

  final String title;
  final String content;
  final String confirmText;
  final String cancelText;

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    return Center(
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: UISpacing.xl),
        decoration: BoxDecoration(
          color: colorScheme.surface,
          borderRadius: BorderRadius.circular(UIBorders.radiusXL),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 8,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 标题
            Padding(
              padding: const EdgeInsets.fromLTRB(
                UISpacing.lg,
                UISpacing.lg,
                UISpacing.lg,
                UISpacing.sm,
              ),
              child: Text(
                title,
                style: UITextStyles.titleLarge.copyWith(
                  color: colorScheme.onSurface,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),

            // 内容
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: UISpacing.lg),
              child: Text(
                content,
                style: UITextStyles.bodyMedium.copyWith(
                  color: colorScheme.onSurfaceVariant,
                ),
              ),
            ),

            // 按钮
            Padding(
              padding: const EdgeInsets.all(UISpacing.lg),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  TextButton(
                    onPressed: () => SmartDialog.dismiss(result: false),
                    child: Text(
                      cancelText,
                      style: UITextStyles.labelLarge.copyWith(
                        color: colorScheme.onSurfaceVariant,
                      ),
                    ),
                  ),
                  const SizedBox(width: UISpacing.sm),
                  ElevatedButton(
                    onPressed: () => SmartDialog.dismiss(result: true),
                    child: Text(confirmText),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}